package cn.peifu.hrm.service.impl;

import cn.peifu.hrm.service.IVerifycodeService;
import cn.peifu.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;


    @Override
    public String createImgVerifycode(String imageCodeKey) {
        //判断Key是否为空
        if(!StringUtils.hasLength(imageCodeKey)){
            throw new RuntimeException("参数非法！");
        }
        //生成UUID随机验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //将验证码存入redis
        redisTemplate.opsForValue().set(imageCodeKey,code,600, TimeUnit.SECONDS);
        String imgaVerifycode = null;
        try {
            imgaVerifycode = VerifyCodeUtils.VerifyCode(140, 75, code);
        } catch (IOException e) {
            throw new RuntimeException("生成图片验证码失败");
        }
        return imgaVerifycode;
    }
}
